package com.example.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * <p>
 * 自定义整数校验实现类
 * </p>
 *
 * @author Chris
 * @since 2022/1/12 11:17
 */
public class CustomRangeValidator implements ConstraintValidator<CustomRange, Object> {

    private static final String REGEX_NUMBER = "\\d+";

    private String min;
    private String max;

    @Override
    public void initialize(CustomRange constraintAnnotation) {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context) {
        String value = obj.toString();

        if (isBlank(value)) {
            return true;
        }

        // 如果当前值、最小值、最大值不是整数
        if (!value.matches(REGEX_NUMBER) || !min.matches(REGEX_NUMBER)
                || !max.matches(REGEX_NUMBER)) {
            return false;
        }

        return Long.parseLong(value) >= Long.parseLong(min) && Long.parseLong(value) <= Long.parseLong(max);
    }

    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for (int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

        }
        return true;
    }

}